<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>do表达式</title>
</head>
<body>
    <h1>do表达式</h1>
    <h2>使块级作用域可以变为表达式</h2>

    <script>
        // 目前的写法
        let x = function() {
            let t = 1;
            t = t * 2;
            return t;
        }();

        // do表达式提案的写法
        /*
        let x = do {
            let t = 1;
            t = t * 2;
            t;
        };
        */

        // 实际应用示例
        // 1. 条件赋值
        /*
        let x = do {
            if (foo()) {
                f();
            } else {
                g();
            }
        };
        */

        // 2. React组件渲染
        /*
        return (
            <nav>
                {do {
                    if (loggedIn) {
                        <LogoutButton />;
                    } else {
                        <LoginButton />;
                    }
                }}
            </nav>
        );
        */

        // 3. 复杂初始化
        /*
        const value = do {
            const headers = new Headers();
            headers.set('Content-Type', 'application/json');
            headers.set('Accept', 'application/json');
            headers;
        };
        */

        // 4. 模拟do表达式
        function doExpression(fn) {
            return fn();
        }

        const result = doExpression(() => {
            const x = 1;
            const y = 2;
            return x + y;
        });

        console.log(result); // 3

        // 5. 条件对象创建
        const config = doExpression(() => {
            const base = {
                api: 'https://api.example.com',
                timeout: 5000
            };

            if (process.env.NODE_ENV === 'development') {
                return {
                    ...base,
                    debug: true,
                    logLevel: 'verbose'
                };
            } else {
                return base;
            }
        });
    </script>
</body>
</html> 